package vashion.azeroth.api.controller.tran;

import java.io.BufferedReader;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import vashion.azeroth.api.controller.base.BaseController;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.tran.PingCallbackService;

import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Refund;
import com.pingplusplus.model.Webhooks;

@Controller
@RequestMapping("/callback")
public class PingCallbackController extends BaseController {

	private final static Logger log = LoggerFactory.getLogger(PingCallbackController.class);
	
	@Autowired
	private PingCallbackService pingCallbackService;
	
	@RequestMapping("pingxxCallback.htm")
	@ResponseBody
	public ApiResult<String> pingxxCallback(HttpServletRequest request, HttpServletResponse response) {
		try {
			//获取头部所有信息
	        Enumeration headerNames = request.getHeaderNames();
	        while (headerNames.hasMoreElements()) {
	            String key = (String) headerNames.nextElement();
	            String value = request.getHeader(key);
	            log.info("ping++回调信息:key=" + key + " value=" + value);
	        }
	        
	        //获得 http body内容
	        BufferedReader reader = request.getReader();
	        StringBuffer buffer = new StringBuffer();
	        String string = null;
	        while (null != (string = reader.readLine())) {
	            buffer.append(string);
	        }
	        
	        // 解析异步通知数据
	        Event event = Webhooks.eventParse(buffer.toString());
	        
	        //扣款成功
	        if ("charge.succeeded".equals(event.getType())) {
	        	Charge charge = (Charge)Webhooks.parseEvnet(buffer.toString());
	        	if(log.isInfoEnabled()) {
	        		log.info(charge.toString());
	        	}
	        	
	        	pingCallbackService.rechargeCallback(charge);
	        	
	        	response.getWriter().write("200");
	        	
	        //退款成功
	        } else if ("refund.succeeded".equals(event.getType())) {
	        	Refund refund = (Refund)Webhooks.parseEvnet(buffer.toString());
	        	pingCallbackService.rebundCallback(refund);
	        //回调状态不正确	
	        } else {
	        	if(log.isInfoEnabled()) {
	        		log.info(event.getType());
	        	}
	        }
			
		} catch(Exception e) {
			log.error("pingxx回调处理异常", e);
		}
		
		return null;
	}
	
}
